package cn.yeamin.ms.config.shiro;

import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.AllowAllCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.yeamin.ms.service.impl.ResourceService;
import cn.yeamin.ms.service.impl.RoleService;
import cn.yeamin.ms.service.impl.UserService;
import cn.yeamin.ms.utils.MD5Utils;
import cn.yeamin.ms.vo.Resource;
import cn.yeamin.ms.vo.Role;
import cn.yeamin.ms.vo.User;
import lombok.extern.slf4j.Slf4j;

/**
 * @packageName: 包名: cn.yeamin.ms.config.shiro
 * @classDesc: 类功能描述:(MyShiroRealm)
 * @author: Administrator
 * @createTime: 2017/7/24 17:23
 * @version: v1.0
 * @copyright:奕明(上海)影视传媒有限公司
 */
@Component
@Slf4j
public class MyShiroRealm extends AuthorizingRealm{

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;


    @Autowired
    private ResourceService resourceService;


    public MyShiroRealm(){
        super(new AllowAllCredentialsMatcher());
        setAuthenticationTokenClass(UsernamePasswordToken.class);
        //暂时禁用Cache
        setCachingEnabled(false);
    }

    /**
     * @methodDesc: 方法描述:(用户授权)
     * @author: 李彤
     * @version: v1.0
     * @copyright:奕明(上海)影视传媒有限公司
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        User user = (User) principals.getPrimaryPrincipal();
        if (log.isInfoEnabled()) {
            log.info("-------------------------【" + user.getUserName() + "】用户授权----------------------");
        }
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //根据用户id查询对应的角色信息
        //根据用户id查询对应的权限资源
        Set<String> shiroPermissions =  new HashSet<String>();
        Set<String> roleSet = new HashSet<String>();
        Set<Role> shiroRoles = roleService.findRoleByUserId(user.getId());
        user.setRoles(shiroRoles);
        Set<Resource> resources = resourceService.findResourceByUserId(user.getId());
        for (Role role : shiroRoles) {
        	role.setResources(resources);
            for (Resource resource : resources) {
                shiroPermissions.add(resource.getSourceKey());
            }
            roleSet.add(role.getRoleKey());
        }
        authorizationInfo.setRoles(roleSet);
        authorizationInfo.setStringPermissions(shiroPermissions);
        return authorizationInfo;
    }

    /**
     * @methodDesc: 方法描述:(身份认证:返回null--->认证失败,返回AuthenticationInfo--->认证成功
     *                      注意(大坑,但不是Bug):如果认证失败会抛出异常,IDEA会认证两次,抛出异常后重新执行该方法,Eclipse是正常则执行一次)
     * @author: 李彤
     * @version: v1.0
     * @copyright:奕明(上海)影视传媒有限公司
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取username
        //String username = (String) token.getPrincipal();
        UsernamePasswordToken myToken = (UsernamePasswordToken)token;
        if (log.isInfoEnabled()) {
            log.info("-------------------------【" + myToken.getUsername() + "】身份认证----------------------");
        }
        //根据username去数据库进行查询
        User record = new User();
        record.setUserName(myToken.getUsername());
        User user = userService.queryOne(record);

        //账号不存在,会抛出UnknownAccountException异常
        if (null == user) {
            throw new UnknownAccountException("账号不存在!");
        }
        //获取密码,myToken.getCredentials()等同于myToken.getPassword()
        String password = new String(myToken.getPassword());
        //密码错误,会抛出IncorrectCredentialsException异常
        if (!MD5Utils.md5(password).equals(user.getPassword())) {
            throw new IncorrectCredentialsException("密码错误");
        }

        // 账号已禁用,可以抛出LockedAccountException(帐号被锁定)或DisabledAccountException(帐号被禁用)
        if (user.getStatus() == 0) {
            throw new DisabledAccountException("账号已冻结,请联系管理员!");
        }
        //三个参数一次为:存放session用户信息principle,传递密码进行与自己进行比对是否一致,获取realm注册bean的id名称
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());

        return info;
    }
}
